import request from '@/utils/request'
import { format } from "@/utils/util";

export default {
	namespaced: true,
	state: {
		queryParams: {
			beginDate: null,// 搜索月份 格式 yyyy-MM
			endDate: null,// 搜索月份 格式：yyyy-MM
			pageNum: 1,
			pageSize: 10
		},
		pointsList: []
	},
	getters: {
		listGroup: state => {
			let monthObj = {}
			let result = []
			if (state.pointsList.length > 0) {
				state.pointsList.forEach(element => {
					let monthKey = format(element.createTime, 'yyyy-MM')
					if (monthObj.hasOwnProperty(monthKey)) {
						monthObj[monthKey].push(element)
					} else {
						monthObj[monthKey] = [element]
					}
				})
				Object.keys(monthObj).forEach((key) => {
					result.push({ monthStr: key, list: monthObj[key]})
				});
			} else if(state.queryParams.beginDate){
				result = [{ monthStr: state.queryParams.beginDate, list: []}]
			}
			return result
		}
	},
	mutations: {
		RESET_QUERYPARAMS(state) {
			state.queryParams = {
				beginDate: null,
				endDate: null,
				pageNum: 1,
				pageSize: 10
			}
		},
		SET_DATE(state, data) {
			state.queryParams.beginDate = data ? format(data, "yyyy-MM") : null
			state.queryParams.endDate = data ? format(data, "yyyy-MM") : null
		},
		SET_LIST(state, data){
			state.pointsList = data
		},
		SET_PAGENUM(state, data) {
			state.queryParams.pageNum = data
		},
	},
	actions: {
		queryList({ commit, state }) {
			return new Promise((resolve, reject) => {
				request.post("/integration/historyList", state.queryParams).then(data => {
					commit('SET_LIST', state.pointsList.concat(data.info))
					commit('SET_PAGENUM', data.page + 1)
					resolve(data)
				}).catch(error => {
					reject(error)
				})
			})
		}

	}
}